<?php
session_start();

require_once "includes/db.php";
require_once "class.userinfo.php";

if (!isset($_GET['hash'])) 
	die("Geen hash gevonden");

$split = explode(",", $_GET['hash']);

if (!(count($split) == 2 && is_numeric($split[0]) && strlen($split[1]) == 31))
	die("Forged hash?");

$user_id = $split[0];

$sql = "SELECT user_name, user_first_name, user_last_name, user_email FROM users WHERE user_id = '" . $user_id . "';";

$result = mysql_query($sql);

if (!$result)
	die("6"); // Technical SQL error

if (mysql_num_rows($result) != 1) 
	die("2"); // Generic SQL error?

$row = mysql_fetch_array($result);

if (!($split[1] == substr(md5($row['user_name'] . "b" . $row['user_first_name'] . "c" . $row['user_last_name'] . "d" . $row['user_email']), 1)))
	die("Incorrect hash, forged?");

if (!isset($_POST['data']))
	die("No POST data found");
	
// best case scenario -> BUSINESS LOGICS!!! :D	
$data = json_decode($_POST['data'], true);

if (json_last_error() == "0" && $data != NULL && COUNT($data)==2) 
{
	$sql = "SELECT `user_id`, `user_first_name`, `user_last_name` FROM `users` WHERE lower(user_first_name) LIKE lower('%".mysql_real_escape_string($data['first_name'])."%') AND lower(user_last_name) LIKE lower('%".mysql_real_escape_string($data['last_name'])."%') LIMIT 0, 10";
	$result = mysql_query($sql);

	if (!$result)
		die("Error #2");

	if (mysql_num_rows($result) == 0)
		die("Error #3");

	$possible_contacts = array();	
		
	while ($row = mysql_fetch_array($result)) 
	{
		$possible_contacts[] = new UserInfo($row['user_id'], $row['user_first_name'], $row['user_last_name']);
	}

	echo json_encode($possible_contacts);
}
else
{
	die("Error #4");
}
?>